<template>
  <div class="starrocks-query-log-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <div class="title-with-back">
          <el-button type="primary" :icon="ArrowLeft" @click="goBack" class="blue-return-button" circle />
          <div class="title-content">
            <div class="title-main">
              <el-icon class="title-icon"><Document /></el-icon>
              <h2>StarRocks 查询日志列表</h2>
            </div>
            <p class="page-description">
              <el-icon><DataAnalysis /></el-icon>
              <span>查询 SQL 审计日志和慢查询记录，支持多维度筛选分析</span>
            </p>
          </div>
        </div>
      </div>

      <!-- 统计卡片 -->
      <div class="page-stats">
        <div class="stat-card total">
          <div class="stat-icon"><el-icon><Menu /></el-icon></div>
          <div class="stat-content">
            <div class="stat-number">{{ total }}</div>
            <div class="stat-label">查询总数</div>
          </div>
        </div>
        <div class="stat-card slow">
          <div class="stat-icon"><el-icon><Timer /></el-icon></div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.slow_query_count }}</div>
            <div class="stat-label">慢查询</div>
          </div>
        </div>
        <div class="stat-card success">
          <div class="stat-icon"><el-icon><Check /></el-icon></div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.success_count }}</div>
            <div class="stat-label">成功</div>
          </div>
        </div>
        <div class="stat-card error">
          <div class="stat-icon"><el-icon><CircleClose /></el-icon></div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.error_count }}</div>
            <div class="stat-label">失败</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索筛选区 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
          </div>
        </template>

        <el-form :model="filterForm" class="search-form">
          <!-- 基础筛选 -->
          <div class="search-form-content">
            <div class="search-form-fields">
              <el-form-item label="集群">
                <el-select v-model="filterForm.cluster" placeholder="全部集群" clearable style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="ETL" value="etl" />
                  <el-option label="API" value="api" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="用户">
                <el-select 
                  v-model="filterForm.queryUser" 
                  placeholder="全部用户" 
                  clearable 
                  filterable
                  style="width: 200px"
                >
                  <el-option label="全部" value="" />
                  <el-option 
                    v-for="user in userOptions" 
                    :key="user" 
                    :label="user" 
                    :value="user" 
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="数据库">
                <el-select 
                  v-model="filterForm.queryDatabase" 
                  placeholder="全部数据库" 
                  clearable 
                  filterable
                  style="width: 200px"
                >
                  <el-option label="全部" value="" />
                  <el-option 
                    v-for="db in databaseOptions" 
                    :key="db" 
                    :label="db" 
                    :value="db" 
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="执行状态">
                <el-select v-model="filterForm.queryState" placeholder="全部状态" clearable style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="OK" value="OK" />
                  <el-option label="EOF" value="EOF" />
                  <el-option label="ERROR" value="ERROR" />
                </el-select>
              </el-form-item>

              <el-form-item label="慢查询">
                <el-select v-model="filterForm.isSlowQuery" placeholder="全部" clearable style="width: 100px">
                  <el-option label="全部" value="" />
                  <el-option label="是" value="1" />
                  <el-option label="否" value="0" />
                </el-select>
              </el-form-item>

              <el-form-item label="查询类型">
                <el-select v-model="filterForm.isQuery" placeholder="全部" clearable style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="查询" value="1" />
                  <el-option label="其他" value="0" />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="search-form-actions">
              <el-button @click="filterExpanded = !filterExpanded">
                <el-icon>
                  <component :is="filterExpanded ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                {{ filterExpanded ? '收起筛选' : '高级筛选' }}
              </el-button>
              <el-button type="primary" @click="handleSearch" :icon="Search" class="search-btn">
                搜索
              </el-button>
              <el-button type="warning" @click="handleReset" :icon="Refresh" class="reset-btn">
                重置
              </el-button>
            </div>
          </div>

          <!-- 高级筛选（可折叠） -->
          <transition name="filter-expand">
            <div v-show="filterExpanded" class="search-form-expanded">
              <div class="search-form-fields">
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="filterForm.timeRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 400px"
                    :clearable="true"
                  />
                </el-form-item>

                <el-form-item label="SQL语句">
                  <el-input 
                    v-model="filterForm.queryStmt" 
                    placeholder="SQL关键字搜索" 
                    clearable
                    style="width: 300px"
                  />
                </el-form-item>
              </div>
            </div>
          </transition>
        </el-form>
      </el-card>
    </div>

    <!-- 表格区 -->
    <div class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>查询日志列表</span>
            </div>
            <div class="table-header-actions">
              <el-button 
                type="success" 
                @click="handleRefresh" 
                :icon="Refresh"
                :loading="loading" 
                size="small"
              >
                刷新
              </el-button>
              <div class="table-info">
                <div class="pagination-control-wrapper" @click="paginationExpanded = !paginationExpanded">
                  <span class="page-count">本页 {{ logList.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">{{ pagination.page }}/{{ Math.ceil(total / pagination.pageSize) || 1 }}</span>
                  <el-icon class="pagination-icon" :class="{ 'expanded': paginationExpanded }">
                    <ArrowDown />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="logList"
          :default-sort="{ prop: 'timestamp', order: 'descending' }"
          @sort-change="handleSortChange"
          style="width: 100%"
          :height="600"
          class="enhanced-table"
        >
          <el-table-column 
            prop="timestamp" 
            label="查询时间" 
            width="180" 
            fixed
            sortable="custom"
            :sort-orders="['descending', 'ascending', null]"
          >
            <template #default="{ row }">
              {{ formatTimestamp(row.query_log_timestamp) }}
            </template>
          </el-table-column>

          <el-table-column prop="cluster" label="集群" width="100">
            <template #default="{ row }">
              <el-tag :type="getClusterTagType(row.cluster)" size="small">
                {{ row.cluster || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="query_user" label="用户" width="140" show-overflow-tooltip />

          <el-table-column prop="query_client" label="客户端" width="150" show-overflow-tooltip />
          
          <el-table-column prop="query_database" label="数据库" width="150" show-overflow-tooltip />
          
          <el-table-column prop="query_state" label="执行状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStateType(row.query_state)" size="small">
                {{ row.query_state }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column 
            prop="perf_time_ms" 
            label="执行时间(ms)" 
            width="140" 
            align="right"
            sortable="custom"
            :sort-orders="['descending', 'ascending', null]"
          >
            <template #default="{ row }">
              <span :class="{ 'slow-query-time': isSlowQueryTime(row.perf_time_ms) }">
                {{ formatNumber(row.perf_time_ms) }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column prop="perf_scan_rows" label="扫描行数" width="130" align="right">
            <template #default="{ row }">
              {{ formatNumber(row.perf_scan_rows) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="perf_return_rows" label="返回行数" width="130" align="right">
            <template #default="{ row }">
              {{ formatNumber(row.perf_return_rows) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="is_slow_query" label="慢查询" width="90" align="center">
            <template #default="{ row }">
              <el-tag v-if="isSlowQuery(row.is_slow_query)" type="warning" size="small">
                <el-icon><Timer /></el-icon>
                是
              </el-tag>
              <el-tag v-else type="success" size="small">
                <el-icon><Check /></el-icon>
                否
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="is_query" label="查询类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag v-if="isQueryType(row.is_query)" type="primary" size="small">
                查询
              </el-tag>
              <el-tag v-else type="info" size="small">
                其他
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="query_stmt" label="SQL语句" min-width="300" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="sql-cell">
                <span class="sql-text">{{ truncateSQL(row.query_stmt) }}</span>
                <el-button
                  v-if="row.query_stmt"
                  size="small"
                  text
                  type="primary"
                  @click.stop="copyToClipboard(row.query_stmt, 'SQL语句')"
                  :icon="CopyDocument"
                  class="copy-btn"
                  title="复制SQL"
                />
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="80" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-tooltip content="查看详情" placement="top">
                  <el-button 
                    type="primary"
                    size="small" 
                    @click="viewDetail(row)" 
                    circle
                  >
                    <el-icon><View /></el-icon>
                  </el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div v-show="paginationExpanded" class="pagination">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[20, 50, 100, 200]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            class="enhanced-pagination"
          />
        </div>
      </el-card>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      width="70%" 
      :close-on-click-modal="false" 
      top="5vh" 
      class="unified-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-icon header-icon-primary"><el-icon><Document /></el-icon></div>
          <div class="header-content">
            <h3>查询日志详情</h3>
            <p>查看 SQL 查询的详细信息</p>
          </div>
        </div>
      </template>

      <div v-if="selectedLog" class="dialog-content">
        <el-descriptions :column="2" border size="default">
          <!-- 基本信息 -->
          <el-descriptions-item label="查询时间">{{ formatTimestamp(selectedLog.query_log_timestamp) }}</el-descriptions-item>
          <el-descriptions-item label="集群">
            <el-tag :type="getClusterTagType(selectedLog.cluster)" size="small">
              {{ selectedLog.cluster || '-' }}
            </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="用户">{{ selectedLog.query_user || '-' }}</el-descriptions-item>
          <el-descriptions-item label="授权用户">{{ selectedLog.query_authorized_user || '-' }}</el-descriptions-item>
          
          <el-descriptions-item label="数据库">{{ selectedLog.query_database || '-' }}</el-descriptions-item>
          <el-descriptions-item label="Catalog">{{ selectedLog.query_catalog || '-' }}</el-descriptions-item>

          <!-- 查询ID 单独一行，因为很长 -->
          <el-descriptions-item label="查询ID" :span="2">
            <div class="detail-trace">
              <span>{{ selectedLog.query_id }}</span>
              <el-button 
                v-if="selectedLog.query_id"
                size="small" 
                text 
                type="primary"
                @click="copyToClipboard(selectedLog.query_id, '查询ID')"
                :icon="CopyDocument"
              >
                复制
              </el-button>
            </div>
          </el-descriptions-item>

          <!-- 状态信息 -->
          <el-descriptions-item label="执行状态">
            <el-tag :type="getStateType(selectedLog.query_state)" size="small">
              {{ selectedLog.query_state }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="查询类型">
            <el-tag v-if="isQueryType(selectedLog.is_query)" type="primary" size="small">
              查询
            </el-tag>
            <el-tag v-else type="info" size="small">
              其他
            </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="慢查询">
            <el-tag v-if="isSlowQuery(selectedLog.is_slow_query)" type="warning" size="small">
              <el-icon><Timer /></el-icon>
              是
            </el-tag>
            <span v-else>否</span>
          </el-descriptions-item>
          <el-descriptions-item label="执行时间">
            <span :class="{ 'slow-query-time': isSlowQueryTime(selectedLog.perf_time_ms) }">
              {{ formatNumber(selectedLog.perf_time_ms) }} ms
            </span>
          </el-descriptions-item>

          <!-- 性能指标 -->
          <el-descriptions-item label="扫描行数">{{ formatNumber(selectedLog.perf_scan_rows) }}</el-descriptions-item>
          <el-descriptions-item label="返回行数">{{ formatNumber(selectedLog.perf_return_rows) }}</el-descriptions-item>
          
          <el-descriptions-item label="扫描字节数">{{ formatBytes(selectedLog.perf_scan_bytes) }}</el-descriptions-item>
          <el-descriptions-item label="客户端地址">{{ selectedLog.query_client || '-' }}</el-descriptions-item>

          <!-- 节点信息 -->
          <el-descriptions-item label="节点类型">{{ selectedLog.node_type || '-' }}</el-descriptions-item>
          <el-descriptions-item label="主机IP">{{ selectedLog.host_ip || '-' }}</el-descriptions-item>

          <el-descriptions-item label="主机名">{{ selectedLog.host_name || '-' }}</el-descriptions-item>

          <!-- 资源信息 -->
          <el-descriptions-item label="资源组" v-if="selectedLog.resource_group">{{ selectedLog.resource_group }}</el-descriptions-item>
          <el-descriptions-item label="Warehouse" v-if="selectedLog.warehouse">{{ selectedLog.warehouse }}</el-descriptions-item>

          <!-- 日志文件信息 -->
          <el-descriptions-item label="日志文件名">{{ selectedLog.log_file_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="组件">{{ selectedLog.component || '-' }}</el-descriptions-item>

          <!-- 错误信息 -->
          <el-descriptions-item label="错误码" :span="2" v-if="selectedLog.query_error_code">
            <el-tag type="danger" size="small">{{ selectedLog.query_error_code }}</el-tag>
          </el-descriptions-item>

          <!-- 日志文件路径 单独一行，因为很长 -->
          <el-descriptions-item label="日志文件路径" :span="2" v-if="selectedLog.log_file_path">
            <div class="detail-trace">
              <span>{{ selectedLog.log_file_path }}</span>
              <el-button 
                size="small" 
                text 
                type="primary"
                @click="copyToClipboard(selectedLog.log_file_path, '日志文件路径')"
                :icon="CopyDocument"
              >
                复制
              </el-button>
            </div>
          </el-descriptions-item>
          
          <el-descriptions-item label="SQL语句" :span="2">
            <div class="detail-sql">
              <el-button 
                v-if="selectedLog.query_stmt"
                size="small" 
                text 
                type="primary"
                @click="copyToClipboard(selectedLog.query_stmt, 'SQL语句')"
                :icon="CopyDocument"
                style="float: right;"
              >
                复制
              </el-button>
              <pre class="sql-content">{{ selectedLog.query_stmt }}</pre>
            </div>
          </el-descriptions-item>
          
          <el-descriptions-item label="原始消息" :span="2" v-if="selectedLog.message">
            <div class="detail-message-container">
              <el-button 
                size="small" 
                text 
                type="primary"
                @click="copyToClipboard(selectedLog.message, '原始消息')"
                :icon="CopyDocument"
                style="float: right;"
              >
                复制
              </el-button>
              <div class="message-content">{{ selectedLog.message }}</div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft, Refresh, Search, Document, DataAnalysis,
  Menu, Timer, Check, CircleClose, List, CopyDocument,
  ArrowDown, ArrowUp, View, Warning
} from '@element-plus/icons-vue'
import api from '@/utils/api'
import { componentLogger } from '@/utils/logger'
import { copyToClipboard as copyTextUtil } from '@/utils/clipboard'

const router = useRouter()

// 状态
const loading = ref(false)
const logList = ref([])
const total = ref(0)
const detailDialogVisible = ref(false)
const selectedLog = ref(null)
const filterExpanded = ref(false)
const paginationExpanded = ref(false)
const userOptions = ref([])
const databaseOptions = ref([])

// 统计数据
const stats = ref({
  slow_query_count: 0,
  success_count: 0,
  error_count: 0
})

// 筛选表单
const filterForm = reactive({
  timeRange: [],
  cluster: '',
  queryUser: '',
  queryDatabase: '',
  queryState: '',
  isSlowQuery: '',
  isQuery: '',
  queryStmt: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 50
})

// 排序状态（使用 timestamp 字段，而不是 query_log_timestamp）
const sortField = ref('timestamp')
const sortOrder = ref('desc')

// 设置默认时间范围：今天0点到当前时刻
const setDefaultTimeRange = () => {
  const now = new Date()
  const startOfToday = new Date()
  startOfToday.setHours(0, 0, 0, 0)
  
  const formatDateTime = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  filterForm.timeRange = [formatDateTime(startOfToday), formatDateTime(now)]
}

// 获取用户列表
const fetchUserOptions = async () => {
  try {
    const response = await api.get('/logs/starrocks-query/users')
    if (response.data && response.data.success) {
      userOptions.value = response.data.data.users || []
    }
  } catch (error) {
    componentLogger.error('获取用户列表失败', error)
  }
}

// 获取数据库列表
const fetchDatabaseOptions = async () => {
  try {
    const response = await api.get('/logs/starrocks-query/databases')
    if (response.data && response.data.success) {
      databaseOptions.value = response.data.data.databases || []
    }
  } catch (error) {
    componentLogger.error('获取数据库列表失败', error)
  }
}

// 获取查询日志列表
const fetchLogs = async () => {
  try {
    loading.value = true
    
    const filters = {}
    
    if (filterForm.timeRange && filterForm.timeRange.length === 2) {
      filters.start_time = filterForm.timeRange[0]
      filters.end_time = filterForm.timeRange[1]
    }
    if (filterForm.cluster) filters.cluster = filterForm.cluster
    if (filterForm.queryUser) filters.query_user = filterForm.queryUser
    if (filterForm.queryDatabase) filters.query_database = filterForm.queryDatabase
    if (filterForm.queryState) filters.query_state = filterForm.queryState
    if (filterForm.isSlowQuery) filters.is_slow_query = filterForm.isSlowQuery
    if (filterForm.isQuery) filters.is_query = filterForm.isQuery
    if (filterForm.queryStmt) filters.query_stmt = filterForm.queryStmt
    
    const response = await api.get('/logs/starrocks-query/logs', {
      params: {
        ...filters,
        page: pagination.page,
        page_size: pagination.pageSize,
        sort: sortField.value,
        order: sortOrder.value
      }
    })
    
    if (response.data && response.data.success) {
      logList.value = response.data.data.logs || []
      total.value = response.data.data.total || 0
      stats.value = response.data.data.stats || stats.value
      componentLogger.info('获取查询日志列表成功', { 
        total: total.value,
        page: pagination.page
      })
    }
  } catch (error) {
    componentLogger.error('获取查询日志列表失败', error)
    ElMessage.error('获取查询日志列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchLogs()
}

// 重置
const handleReset = () => {
  setDefaultTimeRange()
  filterForm.cluster = ''
  filterForm.queryUser = ''
  filterForm.queryDatabase = ''
  filterForm.queryState = ''
  filterForm.isSlowQuery = ''
  filterForm.isQuery = ''
  filterForm.queryStmt = ''
  pagination.page = 1
  fetchLogs()
}

// 刷新
const handleRefresh = () => {
  if (filterForm.timeRange && filterForm.timeRange.length === 2) {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    filterForm.timeRange[1] = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  fetchLogs()
}

// 分页改变
const handlePageChange = (page) => {
  pagination.page = page
  fetchLogs()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchLogs()
}

// 排序改变
const handleSortChange = ({ prop, order }) => {
  if (!prop || !order) {
    sortField.value = 'timestamp'
    sortOrder.value = 'desc'
  } else {
    sortField.value = prop
    sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
  }
  fetchLogs()
}

// 返回
const goBack = () => {
  router.back()
}

// 查看详情
const viewDetail = (row) => {
  selectedLog.value = row
  detailDialogVisible.value = true
}

// 复制到剪贴板
const copyToClipboard = async (text, label = '内容') => {
  await copyTextUtil(text, label)
}

// 获取状态类型
const getStateType = (state) => {
  const types = {
    'OK': 'success',
    'EOF': 'warning',
    'ERROR': 'danger'
  }
  return types[state] || 'info'
}

// 获取集群标签类型（根据集群名称返回不同颜色）
const getClusterTagType = (cluster) => {
  if (!cluster) return 'info'
  
  // 为 etl 和 API 两个集群分配不同颜色
  const clusterColors = {
    'etl': 'primary',   // ETL集群 - 蓝色
    'ETL': 'primary',
    'api': 'success',   // API集群 - 绿色
    'API': 'success'
  }
  
  return clusterColors[cluster] || 'info'  // 默认灰色
}

// 判断是否慢查询（基于 is_slow_query 字段）
const isSlowQuery = (value) => {
  // 兼容多种类型：数字 1、字符串 '1'、布尔值 true
  return value === 1 || value === '1' || value === true
}

// 判断是否查询类型
const isQueryType = (value) => {
  // 兼容多种类型：数字 1、字符串 '1'、布尔值 true
  return value === 1 || value === '1' || value === true
}

// 判断是否慢查询（执行时间>1000ms）
const isSlowQueryTime = (timeMs) => {
  const time = parseInt(timeMs)
  return time > 1000
}

// 截断SQL语句
const truncateSQL = (sql) => {
  if (!sql) return '-'
  if (sql.length <= 100) return sql
  return sql.substring(0, 100) + '...'
}

// 格式化数字
const formatNumber = (value) => {
  if (!value && value !== 0) return '-'
  const num = parseInt(value)
  return num.toLocaleString()
}

// 格式化字节数
const formatBytes = (bytes) => {
  if (!bytes && bytes !== 0) return '-'
  const num = parseInt(bytes)
  if (num < 1024) return num + ' B'
  if (num < 1024 * 1024) return (num / 1024).toFixed(2) + ' KB'
  if (num < 1024 * 1024 * 1024) return (num / 1024 / 1024).toFixed(2) + ' MB'
  return (num / 1024 / 1024 / 1024).toFixed(2) + ' GB'
}

// 格式化时间戳（去掉毫秒）
const formatTimestamp = (timestamp) => {
  if (!timestamp) return '-'
  // 如果包含毫秒（有小数点），截取到秒
  if (timestamp.includes('.')) {
    return timestamp.split('.')[0]
  }
  return timestamp
}

// 初始化
onMounted(() => {
  setDefaultTimeRange()
  fetchUserOptions()
  fetchDatabaseOptions()
  fetchLogs()
  componentLogger.info('StarRocks查询日志列表页面已加载')
})
</script>

<style scoped>
.starrocks-query-log-list {
  padding: 0;
  min-height: calc(100vh - 60px);
}

/* 页面头部 */
.page-header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  border-radius: 12px;
  overflow: hidden;
  color: #303133;
  min-height: 120px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.page-title {
  position: relative;
  z-index: 1;
  display: flex;
  gap: 12px;
  flex: 1;
}

.title-with-back {
  display: flex;
  align-items: flex-start;
  gap: 15px;
}

.blue-return-button {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
  flex-shrink: 0;
  margin-top: 2px;
}

.blue-return-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.4);
  background: linear-gradient(135deg, #66b3ff 0%, #409eff 100%);
}

.title-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.title-main {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
}

.title-main h2 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  letter-spacing: -0.3px;
}

.title-icon {
  color: #409eff;
}

.page-description {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #606266;
  margin: 0;
}

/* 统计卡片 */
.page-stats {
  position: relative;
  z-index: 1;
  display: flex;
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 120px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  font-size: 16px;
}

.stat-card.total .stat-icon {
  background: rgba(144, 147, 153, 0.1);
  color: #909399;
}

.stat-card.slow .stat-icon {
  background: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
}

.stat-card.success .stat-icon {
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.stat-card.error .stat-icon {
  background: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
}

.stat-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

/* 搜索区域 */
.search-section {
  margin-bottom: 24px;
}

.search-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.search-title .el-icon {
  color: #409eff;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.search-form-fields {
  display: flex;
  gap: 16px;
  flex: 1;
}

.search-form-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-form-expanded {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

/* 折叠展开动画 */
.filter-expand-enter-active,
.filter-expand-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.filter-expand-enter-from,
.filter-expand-leave-to {
  opacity: 0;
  max-height: 0;
  margin-top: 0;
  padding-top: 0;
}

.filter-expand-enter-to,
.filter-expand-leave-from {
  opacity: 1;
  max-height: 500px;
  margin-top: 16px;
  padding-top: 16px;
}

/* 按钮样式 */
.search-btn {
  background: linear-gradient(135deg, #409EFF 0%, #66B3FF 100%);
  border: none;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
}

.search-btn:hover {
  background: linear-gradient(135deg, #66B3FF 0%, #409EFF 100%);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
  transform: translateY(-2px);
}

.reset-btn {
  background: linear-gradient(135deg, #E6A23C 0%, #F0C78A 100%);
  border: none;
  border-radius: 8px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
}

.reset-btn:hover {
  background: linear-gradient(135deg, #F0C78A 0%, #E6A23C 100%);
  box-shadow: 0 6px 20px rgba(230, 162, 60, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

/* 表格区域 */
.table-section {
  margin-bottom: 24px;
}

.table-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-title .el-icon {
  color: #409eff;
}

.table-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(64, 158, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  font-size: 12px;
  height: 24px;
}

.pagination-control-wrapper:hover {
  background: rgba(64, 158, 255, 0.12);
  border-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.page-count {
  font-size: 12px;
  font-weight: 500;
  color: #909399;
  line-height: 1;
}

.divider {
  width: 1px;
  height: 12px;
  background: rgba(64, 158, 255, 0.3);
  margin: 0 2px;
}

.pagination-info {
  font-size: 12px;
  font-weight: 500;
  color: #409eff;
  letter-spacing: 0.5px;
  min-width: 24px;
  text-align: center;
  line-height: 1;
}

.pagination-icon {
  font-size: 14px;
  color: #409eff;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  margin-left: 2px;
}

.pagination-icon.expanded {
  transform: rotate(180deg);
}

.enhanced-table {
  border-radius: 12px;
  overflow: hidden;
}

.enhanced-table :deep(.el-table__header-wrapper) th {
  font-size: 14px !important;
  font-weight: 500 !important;
  color: #606266 !important;
  white-space: nowrap !important;
}

.enhanced-table :deep(.el-table__body-wrapper) td {
  font-size: 14px !important;
  white-space: nowrap !important;
}

/* 确保时间列不换行 */
.enhanced-table :deep(.el-table__body-wrapper) td .cell {
  white-space: nowrap !important;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.action-buttons .el-button {
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  width: 32px;
  height: 32px;
  padding: 0;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 详情弹窗 */
.dialog-header {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: 12px;
  font-size: 24px;
}

.header-icon-primary {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  color: #fff;
}

.header-content h3 {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-content p {
  margin: 0;
  font-size: 13px;
  color: #909399;
}

.dialog-content {
  padding: 12px 0;
  max-height: 70vh;
  overflow-y: auto;
}

.detail-trace {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-trace span {
  flex: 1;
  word-break: break-all;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
}

/* 慢查询时间高亮 */
.slow-query-time {
  color: #e6a23c;
  font-weight: 600;
}

/* 详情字段复制按钮（按钮和内容在同一行） */
.detail-trace {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.detail-trace span {
  flex: 1;
  word-break: break-all;
}

/* 原始消息容器 */
.detail-message-container {
  position: relative;
}

.message-content {
  margin: 8px 0 0 0;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.6;
  max-height: 400px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  word-break: break-all;
  overflow-wrap: break-word;
}

/* SQL 单元格样式 */
.sql-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.sql-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
}

.copy-btn {
  flex-shrink: 0;
  padding: 4px 8px !important;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.sql-cell:hover .copy-btn {
  opacity: 1;
}

/* 详情中的 SQL 显示 */
.detail-sql {
  position: relative;
}

.sql-content {
  margin: 8px 0 0 0;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.6;
  max-height: 400px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-all;
}

.normal-query-mark {
  color: #c0c4cc;
}
</style>

